import router from "@/router";
import { useUserStore } from "@/stores/user";
import axios, { AxiosError, type Method } from "axios";
import { ElMessage } from "element-plus";

const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 20 * 1000,
});

//后端返回值类型
export interface ServiceResponse<T> {
  code: number;
  message: string;
  data: T;
}

//4.请求工具函数
export const request = <T>(
  url: string,
  method: Method = "GET",
  submitData?: object
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
  });
};

//请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加token
    const store = useUserStore();
    if (store.token) {
      config.headers!.Authorization = `Bearer ${store.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    //响应拦截器中，减少了一层data ，直接获取后端返回值类型
    return response.data;
  },
  (error) => {
    //如果后端有错误响应（如果没网络就不会进入到判断条件内部）

    if (error.response) {
      // 提示错误信息
      ElMessage.error(error.response.data.message);

      // 根据状态码判断是否登录信息无效
      if (error.response.status === 401) {
        //跳转到登录页
        router.push("/login");
        // 清除token信息
        const store = useUserStore();
        store.clearToken();
      }
    } else {
      //后端没有错误响应
      ElMessage.error("服务器错误，请稍后再试");
    }
    return Promise.reject(error);
  }
);

export default service;
